import { baseURL } from '@/api/_client.ts';
import { getResultDisplay } from '@/api/agriculture.ts';
import { defineStore } from 'pinia';
import { computed, ref } from 'vue';

export const useResultStore = defineStore(
  'ResultStore',
  () => {
    const resultData = ref<any[]>([]);
    const loading = ref<boolean>(false);
    const resultPage = ref({
      currentPage: 1,
      total: 0,
      pageSize: 9,
      showSizePicker: true,
      pageSizes: Array.from({ length: 200 }, (_, index) => index + 1),
    });

    const updateResultData = async () => {
      loading.value = true;
      const req = {
        pageNo: resultPage.value.currentPage,
        pageSize: resultPage.value.pageSize,
      };

      const res = await getResultDisplay(req);
      const { data, meta } = res;

      resultData.value = data.map((item: any) => ({
        id: item.id,
        title: item.attributes.title,
        image: baseURL + `${item.attributes?.image?.data?.attributes?.url}`,
        date: item.attributes.time,
        information: item.attributes.information,
      }));
      resultPage.value.total = meta.pagination.total;
      loading.value = false;
    };

    // 设置分页信息
    const setResultPage = (page?: number) => {
      loading.value = true;
      if (page != null) {
        resultPage.value.currentPage = page;
      }
      loading.value = false;
    };

    const getResultData = computed(() => {
      return resultData.value;
    });

    const getResultPage = computed(() => {
      return resultPage.value;
    });

    const pagination = computed(() => ({
      current: resultPage.value.currentPage,
      total: resultPage.value.total,
      pageSize: resultPage.value.pageSize,
      onChange: (page: number) => {
        setResultPage(page);
        updateResultData().then();
      },
    }));

    const getResultLoading = computed(() => {
      return loading.value;
    });

    return {
      resultData,
      updateResultData,
      getResultData,
      resultPage,
      setResultPage,
      getResultPage,
      pagination,
      getResultLoading,
    };
  },
  {
    persist: true,
  }
);
